package org.xu.upms.server.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.xu.upms.server.common.LoginUser;
import org.xu.upms.server.common.TokenManager;
import org.xu.upms.server.model.User;
import org.xu.upms.server.service.UserService;

import com.xu.commons.model.Result;
import com.xu.commons.model.ResultCode;
import com.xu.commons.until.BaseUntil;
import com.xu.commons.until.CookieUtils;
import com.xu.commons.until.PasswordProvider;
import com.xu.commons.until.StringUtil;
import com.xu.commons.validate.Validator;
import com.xu.commons.validate.annotation.ValidateParam;

@Controller
@RequestMapping("/login")
public class LoginController {
	@Autowired
	UserService userService;
	@Resource
	TokenManager tokenManager;
	@RequestMapping(method = RequestMethod.GET)
	public String login( @RequestParam(required = false) String backUrl,
			 @RequestParam(required = false) String appCode,HttpServletRequest request){
		
		
		
				return "/login";
		
	}
	

	@RequestMapping(method = RequestMethod.POST)
	public String login(
			 @ValidateParam( { Validator.NOT_BLANK }) String backUrl,
			 @ValidateParam({ Validator.NOT_BLANK }) String appCode,
			 @ValidateParam({ Validator.NOT_BLANK }) String account,
			 @ValidateParam({ Validator.NOT_BLANK }) String password,
			 //@ValidateParam({ Validator.NOT_BLANK }) String captcha,
			HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		//1。检验验证码，验证码错误，跳转到登录页面
		
		//2.查询用户 判断用户  是否存在 密码是否错误
		Result result = userService.Login(BaseUntil.getIpAddr(request), appCode, account, PasswordProvider.createPassWord(password));
		//3.登录成功 , 获取token  
		String token="";
		if(result.getCode().equals(ResultCode.SUCCESS)){
			
			User user = (User)result.getData();
			token = CookieUtils.getCookie(request, "token");
			//token为空,或者已过期 ，从新生成token，并放到缓存中，在添加到cookie中
			if(StringUtil.isBlank(token)||tokenManager.validate(token)==null){
				LoginUser loginUser=new LoginUser();
				loginUser.setAccount(user.getAccount());
				loginUser.setUserId(user.getId());
				 token = createToken(loginUser);
				 addTokenInCookie(token,request,response);
			}
			
		}else{
			return "redirect:/login";//跳转到登录界面
		}
		backUrl = URLEncoder.encode(backUrl, "UTF-8");
		
		return "redirect:" + authBackUrl(backUrl, token);
		
	}
	private String authBackUrl(String backUrl, String token) {
		StringBuilder sbf = new StringBuilder(backUrl);
		if (backUrl.indexOf("?") > 0) {
			sbf.append("&");
		}
		else {
			sbf.append("?");
		}
		sbf.append("=").append(token);
		return sbf.toString();
	}

	private String createToken(LoginUser loginUser ) {
		String token = createUUIDId();
		//放到缓存中
		tokenManager.addToken(token, loginUser);
		return token;
	}
	public static String createUUIDId() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replaceAll("-", "");
	}
	private void addTokenInCookie(String token, HttpServletRequest request, HttpServletResponse response) {
		// Cookie添加token
		Cookie cookie = new Cookie("token", token);
		cookie.setPath("/");
		if ("https".equals(request.getScheme())) {
			cookie.setSecure(true);
		}
		cookie.setHttpOnly(true);
		response.addCookie(cookie);
	}
}
